<script>
import { ref, onMounted, onBeforeMount, shallowRef } from 'vue'
import MindMap from 'simple-mind-map'
import { getRequest, postRequest } from '@/http/request'

export default {
  setup() {
    // 使用 ref 创建响应式的 mapData
    const mapData = ref({
      data: {
        uid: 'root',
        text: 'jsMind'
      },
      children: [
        {
          data: {
            uid: 'easy',
            text: 'Easy'
          },
          children: [
            {
              data: {
                uid: 'easy1',
                text: 'Easy to show'
              },
              children: []
            },
            {
              data: {
                uid: 'easy2',
                text: 'Easy to edit'
              },
              children: []
            },
            {
              data: {
                uid: 'easy3',
                text: 'Easy to store'
              },
              children: []
            },
            {
              data: {
                uid: 'easy4',
                text: 'Easy to embed'
              },
              children: []
            }
          ]
        },
        {
          data: {
            uid: 'open',
            text: 'Open Source'
          },
          children: [
            {
              data: {
                uid: 'open1',
                text: 'on GitHub'
              },
              children: []
            },
            {
              data: {
                uid: 'open2',
                text: 'BSD License'
              },
              children: []
            }
          ]
        },
        {
          data: {
            uid: 'powerful',
            text: 'Powerful'
          },
          children: [
            {
              data: {
                uid: 'powerful1',
                text: 'Base on Javascript'
              },
              children: []
            },
            {
              data: {
                uid: 'powerful2',
                text: 'Base on HTML5'
              },
              children: []
            },
            {
              data: {
                uid: 'powerful3',
                text: 'Depends on you'
              },
              children: []
            }
          ]
        },
        {
          data: {
            uid: 'other',
            text: 'test node'
          },
          children: [
            {
              data: {
                uid: 'other1',
                text: "I'm from local variable"
              },
              children: []
            },
            {
              data: {
                uid: 'other2',
                text: 'I can do everything'
              },
              children: []
            }
          ]
        }
      ]
    })

    const clickCount = ref(0)
    const childList = ref([
      {
        data: {
          uid: 'ehsGcHMuoC5oQcx8xMeqsj',
          text: 'topic0',
          is_dir: true,
          expand: false
        },
        children: [
          {
            data: {
              uid: 'TksjZVkuuQQ85Cka86hnWp',
              text: 'topic00',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: '2KPjRHG777cpzYDxZNp9iA',
              text: 'topic01',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: '8v35UFXztjo6EPJJiBQ2NP',
              text: 'topic02',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'cd7SANDgu6Q7MbmhCVqbuD',
              text: 'topic03',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'APNCoUcTX2oLB6F3TL7GMT',
              text: 'topic04',
              expand: false,
              is_dir: true
            },
            children: []
          }
        ]
      },
      {
        data: {
          uid: 'MQuLyC6rnuEgMfheZpsChm',
          text: 'topic1',
          is_dir: true,
          expand: false
        },
        children: [
          {
            data: {
              uid: 'mrmeb2yA6Gx5ejW3nEZUcw',
              text: 'topic10',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'CvpTUR8bYBpoTRhSMx9kvq',
              text: 'topic11',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'NCeM7wrrNLx9aMQimx3DPz',
              text: 'topic12',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'gkfmBw6pFHJttQkknKLh3G',
              text: 'topic13',
              expand: false,
              is_dir: false
            },
            children: []
          },
          {
            data: {
              uid: '4sbSXWbrWNmnaTFsNnBFNJ',
              text: 'topic14',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'PF8b4KTBpyCfWoeSP74xP8',
              text: 'topic15',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'Uuo3moKZd69iVVgJc6QFaZ',
              text: 'topic16',
              expand: false,
              is_dir: true
            },
            children: []
          }
        ]
      },
      {
        data: {
          uid: 'WmXrfMeGVoh8oAXcTxYFai',
          text: 'topic2',
          is_dir: true,
          expand: false
        },
        children: []
      },
      {
        data: {
          uid: 'W6VxyrcGrLj22LwfwqfbCu',
          text: 'topic3',
          is_dir: true,
          expand: false
        },
        children: [
          {
            data: {
              uid: 'SyniZuV8gqFUpr3dsmuFKW',
              text: 'topic30',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'PyfHAJCcLcUWzUsgy38yj3',
              text: 'topic31',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'dgWK3HafGZa4NbSpNAbtFj',
              text: 'topic32',
              expand: false,
              is_dir: true
            },
            children: []
          }
        ]
      },
      {
        data: {
          uid: 'kBNDCfJ5Fw5NwFRf6qy7eJ',
          text: 'topic4',
          is_dir: true,
          expand: false
        },
        children: [
          {
            data: {
              uid: 'P2NTxpEGEzDP2ZSahK37KN',
              text: 'topic40',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'Y4isuHd3xbQFfAqRLsjb5g',
              text: 'topic41',
              expand: false,
              is_dir: true
            },
            children: []
          },
          {
            data: {
              uid: 'BYqi7HP4ZSX83rHWd42hES',
              text: 'topic42',
              expand: false,
              is_dir: false
            },
            children: []
          }
        ]
      }
    ])

    // 定义一个函数，例如用于处理数据或执行特定操作
    //获取思维导图
    const getMindHandle = () => {
      getRequest('/api/commongame/jsmind')
        .then(res => {
          let result = res.result
          let obj = { data: {}, children: [] }
          obj.data.uid = result.id
          obj.data.text = result.topic
          obj.data._dir = result.is_dir //是否是节点列表
          result.children.forEach((e, i, a) => {
            obj.children[i] = { data: {}, children: [] }
            obj.children[i].data.uid = e.id
            obj.children[i].data.text = e.topic
            obj.children[i].data._dir = e.is_dir //是否是节点列表
            if (e.children && Array.isArray(e.children) && e.children.length > 0) {
              e.children.forEach((cEle, cIndex, cArr) => {
                obj.children[i].children[cIndex] = { data: {}, children: [] }
                obj.children[i].children[cIndex].data.uid = cEle.id
                obj.children[i].children[cIndex].data.text = cEle.topic
                obj.children[i].children[cIndex].data.expand = false // 节点是否展开
                obj.children[i].children[cIndex].data._dir = cEle.is_dir //是否是节点列表
              })
            }
          })
          console.log('getMindHandle:')
          console.log(obj)
          mapData.value = obj
          return obj
        })
        .catch(error => {})
    }
    //获取节点下级列表
    const getChildNode = node_id => {
      postRequest('/api/commongame/add', node_id)
        .then(res => {
          let result = res.result
          let obj = []
          result.forEach((ele, item, arr) => {
            obj[item] = { data: {}, children: [] }
            obj[item].data.uid = ele.id
            obj[item].data.text = ele.topic
            obj[item].data.is_dir = ele.is_dir //是否是节点列表
            obj[item].data.expand = false
            obj[item].children = ele.children
            if (ele.children && Array.isArray(ele.children) && ele.children.length > 0) {
              ele.children.forEach((cEle, cIndex, cArr) => {
                obj[item].children[cIndex] = { data: {}, children: [] }
                obj[item].children[cIndex].data.uid = cEle.id
                obj[item].children[cIndex].data.text = cEle.topic
                obj[item].children[cIndex].data.expand = false // 节点是否展开
                obj[item].children[cIndex].data.is_dir = cEle.is_dir //是否是节点列表
                obj[item].children[cIndex].children = cEle.children //是否是节点列表
              })
            }
          })
          console.log('getChildNode:')
          console.log(obj)
          return obj
        })
        .catch(error => {})
    }
    // 删除节点
    const deleteChildNodeHandle = data => {
      postRequest('/api/commongame/delete', data)
        .then(res => {
          if (res.code === 200) {
            console.log('res——delete:' + res)
          }
        })
        .catch(error => {})
    }
    // 更改节点
    const updateChildNodeHandle = data => {
      postRequest('/api/commongame/update', data)
        .then(res => {
          if (res.code === 200) {
            console.log('res-update:' + res)
          }
        })
        .catch(error => {})
    }

    onMounted(async () => {
      const activeNodes = shallowRef([])
      //插入多个子节点
      const insertChildListNode = () => {
        mindMap.execCommand('INSERT_MULTI_CHILD_NODE', [], childList.value)
      }
      const mindMap = new MindMap({
        el: document.getElementById('mindMapContainer'),
        // readonly: true,
        layout: 'mindMap',
        mousewheelAction: 'zoom', //鼠标滚轮的行为，zoom（放大缩小）、move（上下移动）
        isShowExpandNum: false, //节点收起时是否显示收起的数量
        alwaysShowExpandBtn: false, //是否一直显示节点的展开收起按钮，默认为鼠标移上去和激活时才显示
        data: JSON.parse(JSON.stringify(mapData.value))
      })
      await getMindHandle()
      console.log('mindmap')
      console.log(mindMap)
      console.log('mapData.value')
      console.log(mapData.value)
      mindMap.setData(null)
      mindMap.setData(mapData.value)
      console.log('mindMap.on')
      console.log(mindMap.on)
      mindMap.off('node_dblclick')
      mindMap.on('node_click', (node, nodeList) => {
        console.log('点击节点')
        if (node.layerIndex >= 2) {
          // 点击子节点
          let result = getChildNode({ node_id: node.uid })
          console.log(result)
          if (clickCount.value <= 2) {
            insertChildListNode()
          }
          clickCount.value++
          console.log(clickCount.value)
          if (clickCount.value % 2 == 0) {
            console.log('node.show()')
            // node.show()
            node.showChildren()
          } else {
            console.log('node.hide()')
            // node.hide()
            node.hideChildren()
          }
        }

        // console.log('node')
        // console.log(node)
        // console.log('nodeList')
        // console.log(nodeList)
      })
      mindMap.on('data_change', (node, nodeList) => {})
    })
  }
}
</script>

<template>
  <div id="mindMapContainer"></div>
</template>

<style>
/* @import "./simpleMindMap.esm.css"; */

#mindMapContainer {
  width: 100vw;
  height: 100vh;
}

#mindMapContainer * {
  margin: 0;
  padding: 0;
}
</style>
